package cn.hhchat.wp.service;

import cn.hhchat.wp.entity.AttachmentEntity;
import cn.hhchat.wp.entity.PostEntity;
import cn.hhchat.wp.entity.UserEntity;
import cn.hhchat.wp.model.EmailSubject;
import cn.hhchat.wp.util.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * Created this one by HMH on 2017/10/28.
 */
@Service
@Transactional
public class PushService {

    public void pushEmails(List<EmailSubject> emailSubjects) {
        emailSubjects.forEach(e -> emailService.sendHtml(e.getTo(), e.getSubject(), e.getContent()));
    }

    public List<EmailSubject> generatePostNotifyEmail(PostEntity post, List<UserEntity> users) {
        StringBuilder htmlContent = new StringBuilder();
        htmlContent.append("您关注的项目组: ").append(post.getGroup().getName()).append(" 中，").append(post.getPoster().getName()).append(" 于 ").append(DateUtil.formatDateTime(post.getCreateTime())).append(" 提交了一份周报，内容如下。<br><br> ");
        htmlContent.append(post.getContent());
        if (post.getAttachments().size() > 0) {
            htmlContent.append("<br><br><br>" + "附件：<br>");
            for (AttachmentEntity attachment : post.getAttachments()) {
                htmlContent.append("<a href='").append(attachment.getFileUrl()).append("' >").append(attachment.getFileName()).append("</a><br>");
            }
        }

        String subject = "项目组 " + post.getGroup().getName() + " " + post.getYear() + " 年第 " + post.getWeekOfYear() + " 周周报推送";

        return users.stream().map(u -> {
            EmailSubject emailSubject = new EmailSubject();
            emailSubject.setContent(htmlContent.toString());
            emailSubject.setHtml(true);
            emailSubject.setSubject(subject);
            emailSubject.setTo(u.getEmail());
            return emailSubject;
        }).collect(Collectors.toList());
    }

    @Autowired
    private EmailService emailService;

}
